/**
 * 统计数据状态管理
 */
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { statisticsService } from '@/services/statistics.service';
import type {
  StatisticsData,
  EfficiencyAnalysis,
  QualityTrendData,
  Achievement,
  UserLevel,
  CalendarData,
  RankingsData,
  TimeRange,
  RankingType,
  CreationGoal,
  StatisticsReport,
} from '@/types/statistics';
import { message } from 'antd';

interface StatisticsState {
  // State - 统计数据
  statistics: StatisticsData | null;
  efficiencyAnalysis: EfficiencyAnalysis | null;
  qualityTrend: QualityTrendData[];

  // State - 成就和等级
  achievements: Achievement[];
  userLevel: UserLevel | null;

  // State - 日历和排行榜
  calendarData: CalendarData;
  rankings: RankingsData | null;

  // State - 目标
  goals: CreationGoal[];

  // State - 报告
  currentReport: StatisticsReport | null;

  // State - UI状态
  selectedTimeRange: TimeRange;
  selectedRankingType: RankingType;
  loading: boolean;
  error: string | null;

  // Actions - 数据加载
  loadStatistics: (timeRange?: TimeRange) => Promise<void>;
  loadEfficiencyAnalysis: (timeRange?: TimeRange) => Promise<void>;
  loadQualityTrend: (timeRange?: TimeRange) => Promise<void>;
  loadAchievements: () => Promise<void>;
  loadUserLevel: () => Promise<void>;
  loadCalendarData: (year: number, month?: number) => Promise<void>;
  loadRankings: (type?: RankingType, timeRange?: TimeRange) => Promise<void>;
  loadGoals: () => Promise<void>;
  loadReport: (timeRange?: TimeRange) => Promise<void>;

  // Actions - 成就和等级
  unlockAchievement: (achievementId: string) => Promise<void>;
  addExperience: (xp: number, source: string) => Promise<void>;

  // Actions - 目标管理
  createGoal: (goal: Omit<CreationGoal, 'id' | 'current' | 'completed'>) => Promise<void>;
  updateGoalProgress: (goalId: string, current: number) => Promise<void>;
  deleteGoal: (goalId: string) => Promise<void>;

  // Actions - 报告生成
  generateReport: (format: 'pdf' | 'excel', timeRange?: TimeRange) => Promise<void>;
  downloadReport: (format: 'pdf' | 'excel', timeRange?: TimeRange) => Promise<void>;

  // Actions - 事件追踪
  trackEvent: (event: string, metadata?: Record<string, any>) => Promise<void>;

  // Actions - UI状态
  setTimeRange: (timeRange: TimeRange) => void;
  setRankingType: (rankingType: RankingType) => void;

  // Actions - 工具方法
  refreshAll: () => Promise<void>;
  reset: () => void;
}

const initialState = {
  statistics: null,
  efficiencyAnalysis: null,
  qualityTrend: [],
  achievements: [],
  userLevel: null,
  calendarData: {},
  rankings: null,
  goals: [],
  currentReport: null,
  selectedTimeRange: 'month' as TimeRange,
  selectedRankingType: 'words' as RankingType,
  loading: false,
  error: null,
};

export const useStatisticsStore = create<StatisticsState>()(
  devtools(
    persist(
      (set, get) => ({
        ...initialState,

        // ========== 数据加载 ==========

        loadStatistics: async (timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            const statistics = await statisticsService.getStatistics(range);
            set({ statistics, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载统计数据失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadEfficiencyAnalysis: async (timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            const efficiencyAnalysis = await statisticsService.getEfficiencyAnalysis(range);
            set({ efficiencyAnalysis, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载效率分析失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadQualityTrend: async (timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            const qualityTrend = await statisticsService.getQualityTrend(range);
            set({ qualityTrend, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载质量趋势失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadAchievements: async () => {
          set({ loading: true, error: null });

          try {
            const achievements = await statisticsService.getAchievements();
            set({ achievements, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载成就列表失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadUserLevel: async () => {
          set({ loading: true, error: null });

          try {
            const userLevel = await statisticsService.getUserLevel();
            set({ userLevel, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载用户等级失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadCalendarData: async (year: number, month?: number) => {
          set({ loading: true, error: null });

          try {
            const calendarData = await statisticsService.getCreationCalendar(year, month);
            set({ calendarData, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载日历数据失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadRankings: async (type?: RankingType, timeRange?: TimeRange) => {
          const rankingType = type || get().selectedRankingType;
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            const rankings = await statisticsService.getRankings(rankingType, range);
            set({ rankings, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载排行榜失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadGoals: async () => {
          set({ loading: true, error: null });

          try {
            const goals = await statisticsService.getCreationGoals();
            set({ goals, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载目标列表失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        loadReport: async (timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            const currentReport = await statisticsService.getStatisticsReport(range);
            set({ currentReport, loading: false });
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '加载报告失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        // ========== 成就和等级 ==========

        unlockAchievement: async (achievementId: string) => {
          try {
            const updatedAchievement = await statisticsService.unlockAchievement(achievementId);

            set((state) => ({
              achievements: state.achievements.map((ach) =>
                ach.id === achievementId ? updatedAchievement : ach
              ),
            }));

            message.success({
              content: `🎉 解锁成就：${updatedAchievement.name}`,
              duration: 5,
            });

            // 如果有经验奖励，更新用户等级
            if (updatedAchievement.rewards?.xp) {
              await get().loadUserLevel();
            }
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '解锁成就失败';
            message.error(errorMessage);
          }
        },

        addExperience: async (xp: number, source: string) => {
          try {
            const userLevel = await statisticsService.addExperience(xp, source);

            const oldLevel = get().userLevel?.level || 0;
            const newLevel = userLevel.level;

            set({ userLevel });

            // 如果升级了，显示祝贺消息
            if (newLevel > oldLevel) {
              message.success({
                content: `🎊 恭喜升级！当前等级：${newLevel}`,
                duration: 5,
              });
            } else {
              message.success(`+${xp} 经验值 (${source})`);
            }

            // 检查是否解锁新成就
            await get().loadAchievements();
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '增加经验失败';
            message.error(errorMessage);
          }
        },

        // ========== 目标管理 ==========

        createGoal: async (goal: Omit<CreationGoal, 'id' | 'current' | 'completed'>) => {
          set({ loading: true, error: null });

          try {
            const newGoal = await statisticsService.createGoal(goal);

            set((state) => ({
              goals: [...state.goals, newGoal],
              loading: false,
            }));

            message.success('创建目标成功');
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '创建目标失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        updateGoalProgress: async (goalId: string, current: number) => {
          try {
            const updatedGoal = await statisticsService.updateGoalProgress(goalId, current);

            set((state) => ({
              goals: state.goals.map((goal) =>
                goal.id === goalId ? updatedGoal : goal
              ),
            }));

            // 如果完成了目标，显示祝贺消息
            if (updatedGoal.completed) {
              message.success({
                content: `🎯 完成目标：${updatedGoal.metric === 'words' ? `${updatedGoal.target}字` : updatedGoal.metric === 'articles' ? `${updatedGoal.target}篇文章` : `质量分${updatedGoal.target}`}`,
                duration: 5,
              });
            }
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '更新目标进度失败';
            message.error(errorMessage);
          }
        },

        deleteGoal: async (goalId: string) => {
          try {
            await statisticsService.deleteGoal(goalId);

            set((state) => ({
              goals: state.goals.filter((goal) => goal.id !== goalId),
            }));

            message.success('删除目标成功');
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '删除目标失败';
            message.error(errorMessage);
          }
        },

        // ========== 报告生成 ==========

        generateReport: async (format: 'pdf' | 'excel', timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          set({ loading: true, error: null });

          try {
            await statisticsService.generateReport(format, range);
            set({ loading: false });
            message.success(`${format.toUpperCase()}报告生成成功`);
          } catch (error) {
            const errorMessage = error instanceof Error ? error.message : '生成报告失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        downloadReport: async (format: 'pdf' | 'excel', timeRange?: TimeRange) => {
          const range = timeRange || get().selectedTimeRange;
          const hide = message.loading('正在生成报告...', 0);

          try {
            await statisticsService.downloadReport(format, range);
            hide();
            message.success(`${format.toUpperCase()}报告已下载`);
          } catch (error) {
            hide();
            const errorMessage = error instanceof Error ? error.message : '下载报告失败';
            message.error(errorMessage);
          }
        },

        // ========== 事件追踪 ==========

        trackEvent: async (event: string, metadata?: Record<string, any>) => {
          try {
            await statisticsService.trackEvent(event, metadata);
          } catch (error) {
            // 静默失败，不影响用户体验
            console.warn('Failed to track event:', error);
          }
        },

        // ========== UI状态 ==========

        setTimeRange: (timeRange: TimeRange) => {
          set({ selectedTimeRange: timeRange });

          // 自动重新加载相关数据
          const { loadStatistics, loadEfficiencyAnalysis, loadQualityTrend, loadRankings } = get();
          Promise.all([
            loadStatistics(timeRange),
            loadEfficiencyAnalysis(timeRange),
            loadQualityTrend(timeRange),
            loadRankings(undefined, timeRange),
          ]).catch((error) => {
            console.error('Failed to reload data:', error);
          });
        },

        setRankingType: (rankingType: RankingType) => {
          set({ selectedRankingType: rankingType });

          // 自动重新加载排行榜数据
          get().loadRankings(rankingType);
        },

        // ========== 工具方法 ==========

        refreshAll: async () => {
          const hide = message.loading('正在刷新数据...', 0);
          set({ loading: true, error: null });

          try {
            const {
              selectedTimeRange,
              selectedRankingType,
              loadStatistics,
              loadEfficiencyAnalysis,
              loadQualityTrend,
              loadAchievements,
              loadUserLevel,
              loadRankings,
              loadGoals,
            } = get();

            await Promise.all([
              loadStatistics(selectedTimeRange),
              loadEfficiencyAnalysis(selectedTimeRange),
              loadQualityTrend(selectedTimeRange),
              loadAchievements(),
              loadUserLevel(),
              loadRankings(selectedRankingType, selectedTimeRange),
              loadGoals(),
            ]);

            hide();
            message.success('数据刷新成功');
          } catch (error) {
            hide();
            const errorMessage = error instanceof Error ? error.message : '刷新数据失败';
            set({ error: errorMessage, loading: false });
            message.error(errorMessage);
          }
        },

        reset: () => {
          set(initialState);
        },
      }),
      {
        name: 'statistics-storage',
        partialize: (state) => ({
          selectedTimeRange: state.selectedTimeRange,
          selectedRankingType: state.selectedRankingType,
          // 不持久化数据，每次重新加载
        }),
      }
    ),
    { name: 'StatisticsStore' }
  )
);
